<template>
    <el-dialog v-model="outerVisible" 
                title="修改用户信息" 
                @close="closeAddUser" 
                width="30%"
                :close-on-click-modal="false"
                destroy-on-close center draggable>
      <template #default>
        <el-dialog
          v-model="innerVisible"
          width="30%"
          :title="showInfo"
          append-to-body
        />
      </template>
      <template #footer>
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
        >
            <el-form-item label="用户编号" prop="userNum">
                <el-input readonly="readonly" v-model="ruleForm.userNum" style="width: 180px"/>
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
                <el-input v-model="ruleForm.userName" style="width: 180px"/>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="ruleForm.sex" placeholder="选择性别">
                    <el-option label="男" :value=1 />
                    <el-option label="女" :value=0 />
                </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <el-select v-model="ruleForm.roleId" placeholder="选择角色">
                    <el-option
                        v-for="(item,index) in roles"
                        :key="index"
                        :label="item.roleName"
                        :value="item.id"
                        />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)"
                    :loading="updateUserLoading"
                    >更新用户信息
                </el-button>
            </el-form-item>
        </el-form>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
    import { ref, toRefs ,toRef,reactive,watch,computed,PropType,onMounted} from 'vue'
    import type { FormInstance, FormRules } from 'element-plus'
    import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
    import {updateUser} from '@/api/users'

    const formSize = ref('default')
    const ruleFormRef = ref<FormInstance>()
    
    interface userInfoType {
        id:number,
        userNum:string,
        userName:string,
        sex:number,
        roleId:number
    }
    const props = defineProps({
        updateUserShow:Boolean,
        roles:Object,
        userInfo:Object as PropType<userInfoType>
        // userInfo:Object
    })

    const ruleForm = reactive({
        id:'',
        userNum: '',
        userName:'',
        sex: '',
        roleId:'',
    })

    watch(
        ()=>props.userInfo,
        (newVal:any,oldVal:any)=>{
            // console.log(newVal)
            // console.log(oldVal)
            ruleForm.id = newVal.id;
            ruleForm.userName = newVal.userName;
            ruleForm.userNum = newVal.userNum;
            ruleForm.sex = newVal.sex;
            ruleForm.roleId = newVal.roleId;
        },
    )
        
    const showInfo = ref('')

    const rules = reactive<FormRules>({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 10, message: '用户名长度在2到10个字符', trigger: 'blur' },
    ],
    userNum: [
        { required: true, message: '请输入用户编号', trigger: 'blur' },
        { min: 4, max: 8, message: '用户编号长度在4到8个字符', trigger: 'blur' },
    ],
    sex: [
        {
        required: true,
        message: '请选择性别',
        trigger: 'change',
        },
    ],
    roleId: [
        {
        required: true,
        message: '请选择角色',
        trigger: 'change',
        },
    ]
    })

    const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log('submit!')
            submitEditUser();
        } else {
            console.log('error submit!', fields)
        }
    })
    }
    const emit = defineEmits(['closeUpdateUser','updateUserComplete'])

    const updateUserLoading = ref(false);

    const submitEditUser = async()=>{
        updateUserLoading.value = true;
        console.log(ruleForm);       
        try {
            console.log("ruleForm",ruleForm)
            const updateResult:any = await updateUser(ruleForm); 
            updateUserLoading.value = false;
            if(updateResult.success){
                console.log("updateResult",updateResult)
                emit('updateUserComplete');
                outerVisible.value = false;
                ElMessage({
                    type: 'info',
                    message: updateResult.info.msg,
                })
            }else{
                showInfoBox(updateResult.info.msg)
            }
        } catch (error) {
            console.log(error);
            updateUserLoading.value = false;
        }
    }

    const showInfoBox = (info:string)=>{
        showInfo.value = info;
        innerVisible.value = true;
    }

    const outerVisible = computed({
        get() {
            return props.updateUserShow;
        },
        set(v) {
            emit('closeUpdateUser',"close Update user")
        },
    });
   
    const innerVisible = ref(false)

    const closeAddUser = ()=>{
        // console.log("close add user")
        outerVisible.value = false;
    }
  </script>
  <style scoped>
    .dialog-footer button:first-child {
        margin-right: 10px;
    }
  </style>